package com.example.wechat114.controller;

import com.example.wechat114.commons.Constant;
import com.example.wechat114.commons.JsonBean;
import com.example.wechat114.commons.Tools;
import com.example.wechat114.entity.WxMsgCheck;
import com.example.wechat114.service.WechatService;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @author CHENCHEN
 * @create 2021-03-29 14:45
 */
@RestController
public class WechatController {

    @Autowired
    private WechatService wechatService;

    /** Logger实例 */
    static final Logger logger = LoggerFactory.getLogger(WechatController.class);

    /**
     * 开发者填写请求路径，完成微信接入
     * @param wxMsgCheck
     * @return
     */
    @GetMapping("index")
    public String getMsg(WxMsgCheck wxMsgCheck){
        String str = Tools.sortStr(wxMsgCheck.getTimestamp(), wxMsgCheck.getNonce(), Constant.TOKEN);
        String sha1Str = Tools.getSha1Str(str);
        if(sha1Str.equals(wxMsgCheck.getSignature())){
            return wxMsgCheck.getEchostr();
        }
        return "";
    }

    /**
     * 接受用户对公众号的操作，开发者填写url
     * @param request
     * @return
     */
    @PostMapping("index")
    public String postMsg(HttpServletRequest request){
        String resultXml = "";
        try {
            Map<String, String> map = Tools.xmlToMap(request);
            logger.debug(map.toString());
            resultXml = wechatService.handleWxMsg(map);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return resultXml;
    }

    @PostMapping("oAuth")
    public JsonBean oAuthAndJsConfig(String code){

        return wechatService.oAuth(code);
    }

    @PostMapping("jsConfig")
    public JsonBean jsConfig(String url){

        return wechatService.jsConfig(url);
    }

    /**
     * 距离计算测试
     * 实际可以只接受一个前端传入的x,y坐标，去后端数据库取出医院，计算距离
     * @param blongitude
     * @param blatitude
     * @param ulongitude
     * @param ulatitude
     * @return
     */
    @PostMapping("calculateDistance")
    public JsonBean calculateDistance(double blongitude, double blatitude, double ulongitude, double ulatitude){
        double distance = Constant.getDistance(blongitude, blatitude, ulongitude, ulatitude);
        return new JsonBean(0, "", distance);
    }
}
